/*
 * lab3chq21.c
 *
 *  Created on: Mar 6th, 2011
 *      Author: Vishal Verma
 */

/*
 * PROGRAM DESCRIPTION
 *
 * Run I2C bit banged.
 *
 */

/*
 * COMPILER FLAGS
 * sdcc -c --debug -mmcs51 --std-sdcc99 --model-large
 *
 * LINKER FLAGS
 * sdcc --debug -mmcs51 --code-loc 0x0000 --code-size 0x8000 --xram-loc 0x0000 --xram-size 0x8000 --model-large --out-fmt-ihx
 *
 * USAGE SPECIFICATIONS:
 * Baud rate - 57600
 */

/*==============================================INCLUDES=========================================*/
#include <at89c51ed2.h>  //also includes 8052.h and 8051.h
#include <mcs51reg.h>
#include <stdio.h>
#include <stdlib.h>
#include "i2c.h"
#include "lcd.h"

/*==============================================DEFINES==========================================*/
#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0

/*==============================================GLOBALS==========================================*/

enum RETCODE{							//retcodes/parameter flags for all functions
	OK = 0
};

/*=========================================FUNCTION PROTOTYPES===================================*/

void putchar (char c);
char getchar (void);
int putstr (char *s);
int getstr (char *s);
void serialInit(int);
void clearScr(void);
void myDelay(int j);
void initAll(void);

void printMenu(void);


/*=========================================FUNCTION DEFINITIONS===================================*/

/*
* NAME :            _sdcc_external_startup
*
* DESCRIPTION :     Will run before main(). Used to initialize registers etc. as required
*
* INPUTS :
*       PARAMETERS:	-
*		GLOBALS:	AUXR
*
* OUTPUTS :
*       GLOBALS:	AUXR
*       RETURN:		-
*
*/

_sdcc_external_startup() {

	AUXR |= 0x0C;
	AUXR &= 0x7F;
	return 0;
}

/*
* NAME :            putchar
*
* DESCRIPTION :     print 1 character to serial port
*
* INPUTS :
*       PARAMETERS:	char c
*		GLOBALS:	SCON
*
* OUTPUTS :
*       GLOBALS :	SBUF, TI
*       RETURN :	-
*
* PROCESS :
*                   [1]	Wait for port to be ready
* 					[2]	Print char and clear TI
*/

void putchar (char c) {

	while ((SCON & 0x02) == 0);    				// wait for TX ready, spin on TI
	SBUF = c;  									// load serial port with transmit value
	TI = 0;  									// clear TI flag
}

/*
* NAME :            getchar
*
* DESCRIPTION :     get 1 character from serial port
*
* INPUTS :
*       PARAMETERS:	-
*		GLOBALS:	SCON
*
* OUTPUTS :
*       GLOBALS :	SBUF, RI
*       RETURN :	SBUF - character received
*
* PROCESS :
*                   [1]	Wait for character to be received
* 					[2]	Clear RI
*					[3] Return character
*/

char getchar () {

    while ((SCON & 0x01) == 0);  				// wait for character to be received, spin on RI
	RI = 0;										// clear RI flag
	return SBUF;  								// return character from SBUF
}

/*
* NAME :            putstr
*
* DESCRIPTION :     Print a string to serial port
*
* INPUTS :
*       PARAMETERS:	char *s
*		GLOBALS:	-
*
* OUTPUTS :
*       GLOBALS :	-
*       RETURN :	Number of characters transmitted
*
* PROCESS :
*                   [1]  Transmit characters till oxoo (NULL) is encountered
*/

int putstr (char *s) {

	int i = 0;
	while (*s){									// output characters until NULL found
		putchar(*s++);
		i++;
	}
	//putchar('\n\r');
	return i+1;
}

/*
* NAME :            getstr
*
* DESCRIPTION :     Get a string from serial port
*
* INPUTS :
*       PARAMETERS:	char *s
*		GLOBALS:	-
*
* OUTPUTS :
*		PARAMETERS: char *s
*       GLOBALS :	-
*       RETURN :	i - number of characters read
*
* PROCESS :
*                   [1]  Accept characters till 0x0D encountered (CR)
*					[2]	 Store starting at given location (*s)
*
* NOTES :           Is not safe from buffer overrun. Assumes valid memory available for all characters input.
*					Can be substituted with gets() which is equally unsafe but I wrote this so am going with it :)
*/

int getstr (char *s) {

	int i = 0;
	do {
		s[i] = getchar();
		putchar(s[i]);
		i++;
	} while(s[i-1] != 0x0D);  					//0x0D is <CR>
	s[i-1] = 0x00;								//replace <CR> with NULL (0x00)
	putchar('\n\r');
	return (i-1);
}

/*
* NAME :            serialInit
*
* DESCRIPTION :     Initialize the serial port
*
* INPUTS :
*       PARAMETERS:	int br (BAUD RATE)
*		GLOBALS:	-
*
* OUTPUTS :
*       GLOBALS :	PCON, SCON, TMOD, TH1, TR1, TI
*       RETURN :	-
*
*
* NOTES :  Baud rate is supplied as 0xFF for 56700 etc
*/

void serialInit(int br) {

/*
	PCON |= 0x80;								//SMOD1 = 1
	SCON = 0x50;								//uart in mode 1 (8 bit), REN=1
	BDRCON &=0xEC;								//BRR=0; SRC=0;
	BDRCON |=0x0E;								//TBCK=1;RBCK=1; SPD=1
	BRL = br;
	BRL=0xFD;									//115200 Bds at 11.059MHz
	EA = 1;										//Enable serial interrupt
	BDRCON |= 0x10;								//Baud rate generator run
*/


	PCON |= 0x80;								//configure uart, fast baud
	SCON = 0x50;                   			 	//SCON: mode 1, 8-bit UART, enable rcvr
	TMOD |= 0x20;                   			//TMOD: timer 1, mode 2, 8-bit reload for serial
	TMOD |= 0x01;                   			//TMOD: timer 1, mode 2, 8-bit reload for debounce
	TH1 = br;                   				//TH1:  reload value for baudrate
	TR1   = 1;                      			//TR1:  timer 1 run
	TI    = 1;                      			//TI:   set TI to send first char of UART
}

/*
* NAME :            initAll
*
* DESCRIPTION :     Reset global variables to initial values
*
* INPUTS :
*       PARAMETERS:	-
*		GLOBALS:	-
*
* OUTPUTS :
*       GLOBALS :	-
*       RETURN :	-
*/

void initAll() {

	int i = 0;

	EA = 1;
}

/*
* NAME :            clearScr
*
* DESCRIPTION :     Clears and resets the VT100 terminal
*
* INPUTS :
*       PARAMETERS:	-
*		GLOBALS:	-
*
* OUTPUTS :
*       GLOBALS :	-
*       RETURN :	-
*
*
* NOTES :           Will clear the VT100 terminal by sending control sequences to reset and clear entire screen
*					Reset: ESC c
*					Clear Screen: ESC [ 2 J
*/

void clearScr() {
	printf("\033c");			//reset terminal
	printf("\033[2J");			//clear screen
}

/*
* NAME :            myDelay
*
* DESCRIPTION :     Provide a delay
*
* INPUTS :
*       PARAMETERS:	int j - empirical - j=1 ~ 1 second
*		GLOBALS:	-
*
* OUTPUTS :
*       GLOBALS :	-
*       RETURN :	-
*/

void myDelay(int j) {
	int i = 0;
	int cnt = 0;

	j*=100;
	while(j) {
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		for(i=0; i<100; i++);
		j--;
	}
}


void printMenu() {
	clearScr();
	putstr("*******************************WELCOME******************************\n\r");
	putstr("*                                                                  *\n\r");
	putstr("*  This program will use I2C EEPROM and LCD                        *\n\r");
	putstr("*                                                                  *\n\r");
	putstr("********************************************************************\n\n\n\r");
}

/*=========================================FUNCTION MAIN==========================================*/

void main() {

	unsigned int firstFlag = 0;
	unsigned char addr = 0;
	unsigned int i = 0;
	const int size = 20;
	int ret = 0;
	unsigned char string[] = "0123456789aeioulmnop";
	unsigned char buf1[] = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ[]";
	__idata unsigned char buf[128] = ""; /* A null string */

	serialInit(0xFF); 						//0xFF gives Baud Rate 57600
	initAll();
	clearScr();
	P1_7 = ON;								//turn on LED
	TESTPIN = 0;

	printf("Starting...\n\r");
	init_lcd();
	printf("LCD init\n\r");
	clrLcd ();
	printf("LCD clr\n\r");
	lcdputstr(buf1);
	//lcdputstr("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ[]");
	//		   /			   /			   /			   /
	printf("LCD putstr\n\r");

	getchar();
	printf("LCD gotoaddr\n\r");
	clrLcd();
	lcdgotoaddr(0x42);
	lcdputstr("lcdgotoaddr");

	getchar();
	printf("LCD gotoxy\n\r");
	//clrLcd();
	lcdgotoxy(2,5);
	lcdputstr("lcdgotoxy");

	getchar();
	printf("LCD putch\n\r");
	//clrLcd();
	lcdgotoxy(3,0x0D);
	lcdputch('E');
	lcdputch('N');
	lcdputch('D');

	getchar();

	printMenu();

	printf("EEPROM test\n\r");

/*	for (i = 0; i < size ; i++){
		ret = byte_write(i, string[i]);
		printf("Written: %c [%d]\n\r", string[i], ret);
		buf[i] = byte_read(i);
		printf("Read: %c\n\r", buf[i]);
	}
	printf("\n\r");

	for (i = 0; i < size ; i++){
		buf[i] = byte_read(i);
		//printf("Read: %c\n\r", buf[i]);
	}
	buf[size] = 0;
	printf("Read: %s\n\r", buf);*/

/*	if ( page_write( 0x00, "0123456789aeiouxxyyzzz") != SUCCESS )
		printf("page_write() failed!!!\n\r");*/

	printf("seq_read()\n\r");
	seq_read(size, buf, 0x00);
	buf[size] = 0;
	printf("%s\n\r", buf);

	printf("byte_read()\n\r");
	for (i = 0; i < size ; i++){
		buf[i] = byte_read(i);
	}
	buf[size] = 0;
	printf("%s\n\r", buf);



	while (1);
}

